

import { defineStore } from 'pinia'
import { useUserStore, useRouterStore } from '@/store'
import { sleep } from '@/utils/common.js'
export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: undefined,
    permissions: [],
    dictMap: {}
  }),
  actions: {
    setPermissions(permissions) {
      this.permissions = permissions
    },
    setDictMap(dict) {
      const obj = {}
      for (let item of dict) {
        if (!obj[item.dictType] ) {
          obj[item.dictType] = []
        }
        obj[item.dictType].push({
          label: item.label,
          value: item.value
        })
      }
      this.dictMap = obj
    },
    setToken(token) {
      this.accessToken = token
    },
    resetToken() {
      this.$reset()
    },
    toLogin() {
      const { router, route } = useRouterStore()
      router.replace({
        path: '/login',
        // query: route.query,
      })
    },
    async switchCurrentRole(data) {
      this.resetLoginState()
      await nextTick()
      this.setToken(data)
    },
    resetLoginState() {
      const { resetUser } = useUserStore()

      // 重置用户
      resetUser()
      // 重置token
      this.resetToken()
    },
    async logout() {
      this.resetLoginState()
      await sleep(200)
      this.toLogin()
    },
  },
  persist: {
    key: 'erp_auth',
  },
})
